package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    private UserService userService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    @RequestMapping("/findUser")
    public Result findUser(){
        //获取当前登录的用户的用户名
        try {
            User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (user!=null){
                String username = user.getUsername();
                return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,username);
            }
            return new Result(false,MessageConstant.GET_USERNAME_FAIL);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_USERNAME_FAIL);
        }
    }
    /**
     *
     * 修改密码*/
    @RequestMapping("/updatepassword")
    public Result updatepassword(String currentPassword,String newPassword){
        //获取用户用户名
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (user==null){
            return new Result(false,"您当前用户已过期,请重新登录");
        }
        //判断密码是否为空
        if (newPassword==null||newPassword.equals("null")||newPassword.length()==0){
            return new Result(false,"密码不能为空");
        }
        //给密码进行加密
        newPassword = passwordEncoder.encode(newPassword);
        String username = user.getUsername();
        return userService.updatepassword(currentPassword,newPassword,username);
    }

    /*
    * 忘记密码修改密码
    * */
    @RequestMapping("/updatePassword")
    public Result updatePassword(String checkName,String password){
        if (password==null||password.length()==0){
            return new Result(false,"密码不能为空");
        }
        //对密码加密
        String encode = passwordEncoder.encode(password);
        return userService.updateByName(checkName,encode);
    }
}
